<script src="../../../api/warehouseManagement/materialInfo.js"></script>
<template>
  <div class="tenantMenu_main main_container user_container">
    <div class="main_header">
      <div class="padding_container">
        <div class="left"><Breadcrumb /></div>
        <div class="right">
          <HeaderOperation :parent="this" />
        </div>
      </div>
    </div>
    <div v-loading="loading" class="main_main">
      <search-bar-new :parent="this" />
      <div class="main_main_container">

        <div class="main_main_left">
          <div class="main_main_left_top">
            <el-tree
              ref="tree"
              :data="deptData"
              node-key="id"
              :expand-on-click-node="false"
              :default-expand-all="true"
              :highlight-current="true"
              @node-click="treeNodeClick"
            >
              <span slot-scope="{ node, data }" class="tree-node">
                <span class="node_name">{{ data.name }}</span>
                <span class="node_operate">
                  <a class="node_operate_item" @click.stop="addNext(data)">
                    <svg-icon icon-class="树新增" />
                  </a>
                  <a v-if="node.level>1" class="node_operate_item" @click.stop="editDept(data)">
                    <svg-icon icon-class="树编辑" />
                  </a>
                  <a v-if="node.level>1" class="node_operate_item" @click.stop="delDept(data)">
                    <svg-icon icon-class="树删除" />
                  </a>
                </span>
              </span>
            </el-tree>
          </div>
          <div class="main_main_left_bottom">
            <a :class="activeNum==2?'active':''" @click.stop="unassignedUser">
              <div class="main_main_left_bottom_item">被停用物料</div>
            </a>
          </div>
        </div>
        <div class="main_main_right">
          <div class="main_main_right_header">
            <div class="main_main_right_header_left">
              <span>{{ currentDeptName }}</span>
            </div>
          </div>
          <div ref="table_container" class="table_container">
            <el-table
              v-if="tableColumns.length>0"
              ref="table"
              :data="tableData"
              stripe
              border
              :height="tableHeight"
              style="width: 99.9%"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              :cell-style="cellStyle"
              @cell-click="cellClick"
              @sort-change="(column)=>{sortChange(column, this)}"
              @selection-change="(val)=>{selectionChange(val, this)}"
            >
              <el-table-column type="selection" width="70" align="center" />
              <Column v-for="(column,index) in tableColumns" :key="index" :prop="column.prop" :is-show="column.isShow" :label="column.label" :sortable="column.sortable" :width="column.width" :min-width="column.minWidth" :column-type="column.columnType" />
              <el-table-column
                label="附件"
                min-width="80"
              >
                <template slot-scope="scope">
                  <FileManage
                    :file-names="scope.row.docFileName"
                    :file-real-names="scope.row.docFileRealName"
                    :file-urls="scope.row.docFileUrl"
                    :readonly="true"
                    class="accessory"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" fixed="right" width="180">
                <template slot-scope="scope">
                  <el-button
                    v-hasPermi="['wms:material:edit']"
                    type="text"
                    @click.stop="edit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    v-hasPermi="['wms:material:delete']"
                    type="text"
                    @click.stop="deleteOne(scope.row)"
                  >删除</el-button>
                  <span v-if="scope.row.isAdmin=='1'" class="el-button--text button_grey">删除</span>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div class="main_bottom">
            <pagination
              :total="total"
              :page.sync="pageData.pageNum"
              :limit.sync="pageData.pageSize"
              :selected-num="selectionsAll.length"
              @pagination="getList"
            />
          </div>
        </div>
      </div>

    </div>
    <PrintMaterialInfo_large ref="print" :print-data="printData_large" />
    <PrintMaterialInfo_small ref="print" :print-data="printData_small" />
  </div>
</template>

<script>
import { materialClassificationList,getInfo, list, remove, importMethod, materialClassificationRemove } from '@/api/warehouseManagement/materialInfo'
import AddMaterialType from '@/views/warehouseManagement/materialInfo/addMaterialType' // 新增或编辑页面
import AddOrUpdate from '@/views/warehouseManagement/materialInfo/addOrUpdate' // 新增或编辑页面
import ShowDetail from '@/components/JLINK2/common/ShowDetailTitle' // 查看页面
import { getDictSelects } from '@/api/common/common'
import { mapGetters } from 'vuex'
import PrintMaterialInfo_large from '@/components/print/PrintMaterialInfo_large'
import PrintMaterialInfo_small from '@/components/print/PrintMaterialInfo_small'
export default {
  name: 'Index',
  components: { PrintMaterialInfo_large, PrintMaterialInfo_small }, // 组件注册
  computed: {
    ...mapGetters([
      'isAdmin', 'userName'
    ])
  },
  data() {
    return {
      activeNum: 1,
      deptData: [],
      materialTypeIds: '',
      currentDeptName: '',
      loading: true,
      pageId: '物料信息', // 页面唯一标识
      pageExportId: '物料信息导出', // 页面导出标识
      pageData: {
        pageNum: 1,
        pageSize: 20,
        orderByColumn: 'updateTime',
        isAsc: 'desc',
        status: '1'
      },
      pageData2: {
        pageNum: 1,
        pageSize: 9999,
        orderByColumn: 'updateTime',
        isAsc: 'desc'
      },
      codeStatus: true,
      total: 1, // 数据一共有多少条
      mainId: 'id', // 表格行ID
      tableHeight: '0', // 表格高度
      tableData: [], // 表格数据
      tableColumns: [], // 表格实际用的字段
      searchColumns: [], // 搜索区实际用的字段
      selections: [], // 表格当前页所选中的行
      selectionsAll: [], // 表格所有页选中的行
      defaultTableColumns: [// 表格常规字段（初始值）
        { prop: 'statusName', label: '状态', minWidth: '160', isShow: false },
        { prop: 'imgUrl', label: '物料配图', minWidth: '80', columnType: 'picture', canOrder: false },
        { prop: 'materialCode', label: '物料编码', minWidth: '200' },
        { prop: 'materialName', label: '物料名称', minWidth: '200', canOrder: false },
        { prop: 'materialModel', label: '规格型号', canOrder: false },
        { prop: 'materialUnitName', label: '物料单位', canOrder: false },
        { prop: 'materialTypeName', label: '物料分类', canOrder: false },
        { prop: 'descriptionName', label: '物料属性', canOrder: false },
        { prop: 'weight', label: '重量', canOrder: false },
        { prop: 'texture', label: '材质', canOrder: false },
        { prop: 'brand', label: '品牌', canOrder: false },
        { prop: 'qualityGuaranteePeriod', label: '保质期(天)', canOrder: false },
        { prop: 'minimumInventory', label: '最小库存量', minWidth: this.SETTINGS.settings_decimalDigits_length, canOrder: false },
        { prop: 'maximumInventory', label: '最大库存量', minWidth: this.SETTINGS.settings_decimalDigits_length, canOrder: false },
        { prop: 'remark', label: '备注', canOrder: false }

      ],
      exportTableColumns: [// 表格常规字段（初始值）
        { prop: 'materialCode', label: '物料编码', minWidth: '200' },
        { prop: 'materialName', label: '物料名称', minWidth: '200', canOrder: false },
        { prop: 'materialModel', label: '规格型号', canOrder: false },
        { prop: 'materialUnitName', label: '物料单位', canOrder: false },
        { prop: 'materialTypeName', label: '物料分类', canOrder: false },
        { prop: 'descriptionName', label: '物料属性', canOrder: false },
        { prop: 'weight', label: '重量', canOrder: false },
        { prop: 'texture', label: '材质', canOrder: false },
        { prop: 'brand', label: '品牌', canOrder: false },
        { prop: 'qualityGuaranteePeriod', label: '保质期(天)', canOrder: false },
        { prop: 'minimumInventory', label: '最小库存量', minWidth: this.SETTINGS.settings_decimalDigits_length, canOrder: false },
        { prop: 'maximumInventory', label: '最大库存量', minWidth: this.SETTINGS.settings_decimalDigits_length, canOrder: false },
        { prop: 'remark', label: '备注', canOrder: false }
      ],
      defaultExport: [],
      defaultSearchColumns: [// 搜索区常规字段（初始值）
        { prop: 'searchValue', label: '模糊搜索', type: 'input' },
        { prop: 'status', label: '状态', type: 'select', optionsName: 'statusOptions2', isShow: false },
        { prop: 'materialUnitId', label: '物料单位', type: 'dict', optionsName: 'materialUnitOptions' },
        { prop: 'descriptionId', label: '物料属性', type: 'dict', optionsName: 'descriptionOptions' }
      ],
      operationData: [ // 右上角的操作按钮
        { label: '新增', perm: 'wms:material:add' },
        { label: '导入', perm: 'wms:material:import' },
        { label: '批量删除', perm: 'wms:material:delete' },
        { label: '批量导出3', perm: 'wms:material:export' },
        { label: '打印', perm: '' },
        { label: '页面配置', perm: '' }
      ],
      printData_large: [],
      printData_small: [],
      allTableData: [],
      statusOptions2: [ // 选择组件数据源
        { value: undefined, label: '全部' },
        { value: 1, label: '启用' },
        { value: 0, label: '停用' }
      ],
      materialUnitOptions: [],
      descriptionOptions: [],
      showKey: {
        type: 'column_two',
        keys: [
          { type: 'form', name: '物料编码', key: 'materialCode' }, // type: 'form' 表示是普通的表单展示
          { type: 'form', name: '物料名称', key: 'materialName' },
          { type: 'form', name: '规格型号', key: 'materialModel' },
          { type: 'form', name: '物料单位', key: 'materialUnitName' },
          { type: 'form', name: '物料分类', key: 'materialTypeName' }, // length:'double' 表示占两列
          { type: 'form', name: '物料属性', key: 'descriptionName' },
          { type: 'form', name: '重量', key: 'weight' },
          { type: 'form', name: '材质', key: 'texture' },
          { type: 'form', name: '品牌', key: 'brand' },
          { type: 'form', key: 'qualityGuaranteePeriod', name: '保质期(天)' },
          { type: 'form', key: 'minimumInventory', name: '最小库存量' },
          { type: 'form', name: '最大库存量', key: 'maximumInventory' },
          { type: 'form', name: '备注', key: 'remark', length: 'double' },
          { type: 'form', name: '状态', key: 'statusName' },
          { type: 'file', name: '物料配图', fileName: 'imgName', fileRealName: 'imgRealName', fileUrl: 'imgUrl' },
          { type: 'file', name: '附件', fileName: 'docFileName', fileRealName: 'docFileRealName', fileUrl: 'docFileUrl' },
          { type: 'table', name: '附加件信息', key: 'details', columns: [ // type: 'table' 表示是表格
              { type: 'column', name: '物料编码', key: 'materialCode' },
              { type: 'column', name: '物料名称', key: 'materialName' },
              { type: 'column', name: '数量', key: 'num' },
              { type: 'column', name: '替代料', key: 'replaceMaterialName' },
              { type: 'column', name: '备注', key: 'remark' },
              { type: 'column', name: '默认', key: 'isDefault' }
            ] }
        ]
      }
    }
  },
  mounted() {
    this.codeStatus = this.$store.state.user.codeStatus
    this.getDeptTree()
    this.getDictOptions()
  },
  methods: {
    cellStyle({ row, column }) {
      if (column.property == 'materialCode') {
        return {
          cursor: 'pointer',
          color: '#387bfc'
        }
      }
    },
    cellClick(row, column, cell) {
      switch (column.property) {
        case 'materialCode':
          this.showDetail(row)
          break
      }
    },
    showDetail(row) {
      getInfo(row.id).then(res => {
        console.log(res.data,999999)
        // 此处展示的页面有是否默认字段，后端给的是1，前端处理成 是
        if (res.data.details && res.data.details.length > 0) {
          res.data.details.forEach(item => { item.isDefault == '1' ? item.isDefault = '是' : item.isDefault = '' })
        }
        this.$layer.iframe({// 弹框
          content: {
            content: ShowDetail, // 传递的组件对象
            parent: this, // 当前的vue对象
            data: {
              showData: res.data,
              showKey: this.showKey
            }// props
          },
          area: ['1320px', '700px'],
          title: '查看物料信息', // 标题
          shadeClose: false // 点击遮罩是否关闭
        })
      })
    },
    getDictOptions() {
      getDictSelects('materialUnitId').then(res => {
        this.materialUnitOptions = res.data
      })
      getDictSelects('descriptionId').then(res => {
        this.descriptionOptions = res.data
      })
    },
    importMethod(files) { // 导入接口
      importMethod(files).then(res => {
        if (res.code == 200) {
          this.$message.success('导入成功')
          this.getList()
        }
      })
    },
    getExportData(data) {
      return list(data)
    },
    deptOneClick() { // 默认点击一下第一级部门
      document.querySelector('.el-tree-node__content').click()
    },
    getLists() {
      list(this.pageData2).then(res => {
        this.allTableData = res.data

        this.$nextTick(() => {
          this.tableHeight = document.getElementsByClassName('main_main')[0].clientHeight -
            document.getElementsByClassName('SearchBar_main')[0].clientHeight - 120
        })
      })
    },
    unassignedUser() { // 被停用物料
      this.activeNum = 2
      this.currentDeptName = '被停用物料'
      this.pageData.pageNum = 1
      this.$refs['tree'].setCurrentKey()
      Object.keys(this.pageData).forEach(key => { // 给右边数据赋值
        if (key !== 'pageNum' && key !== 'pageSize' && key !== 'orderByColumn' && key !== 'isAsc') {
          this.pageData[key] = ''
        }
      })
      this.pageData.status = 0
      this.getList()
    },
    getDeptTree() {
      materialClassificationList().then(res => {
        this.deptData = res.data
        this.$nextTick(() => {
          this.deptOneClick()
        })
      })
    },
    getList() {
      this.tableData = []
      const cachePageData = this.$deepClone(this.pageData)
        cachePageData.materialTypeIds = this.materialTypeIds
        list(cachePageData).then(res => {
          this.tableData = res.data
          this.total = res.total
          this.$nextTick(() => {
            this.setSelectRow(this)// 设置行选中

            this.tableHeight = document.getElementsByClassName('main_main')[0].clientHeight -
              document.getElementsByClassName('SearchBar_main')[0].clientHeight - 120
          })
        })
    },
    addNext(data) { // 新增下级部门
      this.$layer.iframe({// 弹框
        content: {
          content: AddMaterialType, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
              parentId: data.id,
              parentName: data.name,
              increased: true
          }// props
        },
        area: ['440px', '400px'],
        title: '新增物料分类', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    editDept(data) { // 编辑部门
      this.$layer.iframe({// 弹框
        content: {
          content: AddMaterialType, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            parentId: data.id,
            parentName: data.name,
            increased: false
          }// props
        },
        area: ['440px', '400px'],
        title: '编辑物料分类', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    delDept(data) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        materialClassificationRemove(data.id).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.getDeptTree()
        })
      }).catch(() => {})
    },
    treeNodeClick(data) { // 点击树节点
      this.activeNum = 1
      this.currentDeptName = data.name
      this.materialTypeIds = data.id
      this.pageData.pageNum = 1
      this.pageData.status = 1
      Object.keys(this.pageData).forEach(key => { // 给右边数据赋值
        if (key !== 'pageNum' && key !== 'pageSize' && key !== 'orderByColumn' && key !== 'isAsc' && key !== 'status') {
          this.pageData[key] = ''
        }
      })
      this.getList()
    },
    add() {
          this.$layer.iframe({// 弹框
            content: {
              content: AddOrUpdate, // 传递的组件对象
              parent: this, // 当前的vue对象
              data: {
              }// props
            },
            area: ['1230px', '700px'],
            title: '新增物料信息', // 标题
            shadeClose: false // 点击遮罩是否关闭
          })
    },
    edit(row) {
      this.$layer.iframe({// 弹框
        content: {
          content: AddOrUpdate, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            id: row[this.mainId]
          }// props
        },
        area: ['1230px', '700px'],
        title: '编辑物料信息', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    deleteOne(row) {
      const _this = this
      this.$confirm('确定要删除吗', '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消', cancelButtonClass: 'cancelConfirm',
        type: 'warning'
      }).then(function() {
        remove( row[_this.mainId] ).then(res => {
          _this.$message({
            message: res.msg,
            type: 'success'
          })
          _this.getList()
        })
      }).catch(() => {})
    },
    getPrintData(data) {
      return list(data)
    },
    // 当前页的删除接口
    deleteMethod(deleteIds) {
      return remove({ deleteIds: deleteIds })
    }
  }
}
</script>
<style>
</style>
<style lang="less" scoped>
.main_main{
  height: calc(100% - 50px);
}
.main_main_container{
  width: 100%;
  height: calc(100% - 50px);
  display: flex;

  .main_main_left{
    width: 25%;
    height: calc(100% - 20px);
    margin-top: 20px;
    border-right: 1px solid rgba(51, 51, 51, 0.5);
    border-top: 2px solid rgba(51, 51, 51, 0.5);
    .main_main_left_top{
      width: 100%;
      height: calc(100% - 57px);
      overflow-y: auto;
      .el-tree{
        background-color: transparent;
      }
      /deep/ .el-tree-node__content:hover{
        background-color: rgba(56,123,252,0.5) !important;
        color: white;
      }
    }
    .main_main_left_bottom{
      width: 100%;
      .main_main_left_bottom_item{
        background-color: rgba(74, 77, 82, 0.2);
        height: 40px;
        display: flex;justify-content: flex-start;align-items: center;padding-left: 24px;
      }
      .main_main_left_bottom_item:last-child{
        border-top: 1px solid white;
      }
      .main_main_left_bottom_item:hover{
        background-color: rgba(56,123,252,.5);
        color: white;
      }
      .active{
        .main_main_left_bottom_item{
          background-color: rgba(56,123,252,1);
          color: white;
        }
      }
    }
  }
  .max_user{
    color: rgb(248, 146, 12);
    font-size: 12px;
    margin-left: 20px;
  }
  .main_main_right{
    width: 75%;
    height: 100%;
    display: flex;
    flex-direction: column;
  }
  .changeSuperAdmin{
    width: 120px;
  }
}
</style>
